import {useEffect, useRef, useState} from 'react'
import Taro, {useReady, useRouter} from '@tarojs/taro'
import {getComment, getSightInfoDetail, selectDidLike, selectLike} from '@/packageA/api/scene'
import {useRoutePlan} from '@/hooks'

export interface SightInfoDetail {
  address: string
  areaId: string
  areaName: string
  attention: string
  collectNum: number
  commentNum: number
  content: string
  coupon: string
  id: string
  imgList: string[]
  lat: string
  likeNum: number
  isCollect: boolean
  isLike: boolean
  lon: string
  name: string
  openTime: string
  price: string
  proId: string
  proName: null | string
  summary: string
}

export interface CommentItem {
  content: string
  createTime: string
  id: string
  isLike: boolean
  likeNum: number
  parentId: number
  sightId: number
  twoComment: []
  userId: string
  userInfo: {
    avatarUrl: string
    id: string
    nickname: string
  }
}

/**
 * 评论区显示隐藏
 */
export const useCommentShow = () => {
  const [show, setShow] = useState(false)
  const [focus, setFocus] = useState(false)

  function onShowComment () {
    setShow(true)
    setTimeout(() => {
      setFocus(true)
    }, 300)
  }

  function onBack () {
    setShow(false)
    setFocus(false)
  }

  return {
    show, focus, onShowComment, onBack
  }
}

/**
 * 获取请求数据
 */
export const useOperateData = () => {
  const {params} = useRouter<{ id: string }>()
  const [sightInfoDetail, setSightInfoDetail] = useState<Partial<SightInfoDetail>>({})
  const [commentList, setCommentList] = useState<CommentItem[]>([])
  const {routeScrollTo, geocoder} = useRoutePlan()
  const [location, setLocation] = useState<{
    latitude: number,
    longitude: number
  } | null>(null)
  let timer = useRef<NodeJS.Timeout>()

  useEffect(() => {
    if (!sightInfoDetail.address) return
    if (sightInfoDetail.lat && sightInfoDetail.lon) {
      setLocation({
        latitude: +sightInfoDetail.lat,
        longitude: +sightInfoDetail.lon
      })
      return
    }
    geocoder(sightInfoDetail.address).then((res: any) => {
      setLocation({
        latitude: res.location.lat,
        longitude: res.location.lon
      })
    })
  }, [sightInfoDetail.address, sightInfoDetail.lat, sightInfoDetail.lon])

  function navigator (url: string) {
    console.log(url, location)
    if (url.search('/Travel/Travel') > -1 && location) {
      routeScrollTo({
        ...location,
        name: sightInfoDetail.address as string
      })
      return
    }
    Taro.navigateTo({
      url: url + `?sightId=${sightInfoDetail.id}&title=${sightInfoDetail.areaName}`
    })
  }

  useReady(() => {
    getSightInfoDetail(params.id).then(res => {
      setSightInfoDetail(res)
    })
    getCommentDetail()
  })

  async function getCommentDetail (): Promise<boolean> {
    let res: CommentItem[] = await getComment(params.id)
    setCommentList(res.reverse())
    return true
  }

  function toggleLike (id: string, index: number) {
    if (timer.current) {
      clearTimeout(timer.current)
    }

    timer.current = setTimeout(() => {
      selectLike(id).then(res => {
        console.log(res)
      })
    }, 200)
    setCommentList(prevState => {
      if (prevState[index].id === id) {
        prevState[index].isLike = !prevState[index].isLike
      }
      timer.current = setTimeout(() => {
        if (prevState[index].isLike) {
          selectLike(id)
        } else {
          selectDidLike(id)
        }
      }, 200)
      return prevState.slice()
    })
  }
  return {
    sightInfoDetail, commentList, navigator,
    getCommentDetail, toggleLike
  }
}
